using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ErrorDumper.Providing {
    public class DirectoryExceptionProvider : IExceptionProvider {

        public DirectoryExceptionProvider(string directory) {
            if (string.IsNullOrEmpty(_directory = directory))
                throw new ArgumentException("is null or empty", "directory");
        }

        public DirectoryExceptionProvider() {
            _directory = ExceptionDataSource.Current.PhysicalPath;
        }

        readonly string _directory;

        public int GetCount(ExceptionQuery query) {
            throw new NotImplementedException();
        }

        public ICollection<ExceptionHeader> GetHeaders(ExceptionQuery query) {
            if (query == null)
                throw new ArgumentNullException("query");
            if (!query.WriteUtcFrom.HasValue)
                throw new NotSupportedException();

            var directory = new DirectoryInfo(_directory);

            if (!directory.Exists)
                return new ExceptionHeader[0];

            var files = directory.GetFiles().Where(i => i.CreationTimeUtc >= query.WriteUtcFrom).ToList();
            if (files.Count == 0)
                return new ExceptionHeader[0];

            var result = new List<ExceptionHeader>();

            foreach (var file in files) {
                var header = new ExceptionHeader();
                header.Properties.AddRange(ExceptionSerializer.DeserializeProperties(file.Open(FileMode.Open)));
                result.Add(header);
            }

            return result;
        }

        public ICollection<ExceptionHeader> GetHeaders(IEnumerable<string> handles) {
            throw new NotImplementedException();
        }

        public string GetContent(string handle) {
            throw new NotImplementedException();
        }

        public int Delete(ExceptionQuery query) {
            throw new NotImplementedException();
        }

        public int Delete(IEnumerable<string> handles) {
            throw new NotImplementedException();
        }
    }
}
